import { reactive, readonly, ref } from 'vue'
import { AppInfo, PageInfo, EditPageConfig } from './usePageJson.type'
import { AppListItem } from '@/store/app.type'

// 当前编辑应用的 id
const currentAppId = ref('')

// 当前编辑的页面
const currentPage = ref(sessionStorage.getItem('currentPage'))

// 当前编辑的组件
const currentCom = ref(sessionStorage.getItem('currentCom'))

// 当前编辑应用的数据
const appInfo: AppInfo = reactive({
  id: '',
  name: '',
  desc: '',
  actions: {}, // 全局方法
  models: [], // 数据
  pages: [],
})

// 设置应用的基础信息
const setAppBasic = (basic: AppListItem) => {
  appInfo.id = basic.id
  appInfo.name = basic.name
  appInfo.desc = basic.desc
}

// 创建页面
const addAppPage = (page: Omit<PageInfo, 'type'>) => {
  appInfo.pages.push({
    type: 'page',
    key: page.key,
    name: page.name,
    components: page.components ?? [],
    config: page.config,
  })
}

// 修改页面配置
const editPageConfig = (pageKey: string, config: EditPageConfig) => {
  const pageIdx = appInfo.pages.findIndex((item) => {
    return item.key === pageKey
  })

  appInfo.pages[pageIdx].name = config.name
  appInfo.pages[pageIdx].config = {
    height: config.height,
    backgroundColor: config.backgroundColor,
    backgroundImage: config.backgroundImage,
    backgroundSize: config.backgroundSize,
    backgroundRepeat: config.backgroundRepeat,
  }
}

// 切换编辑的页面
const changeCurrentPage = (key: string) => {
  currentPage.value = key
  sessionStorage.setItem('currentPage', key)
}

// 切换编辑的组件
const changeCurrentCom = (key: string) => {
  currentCom.value = key
  sessionStorage.setItem('currentCom', key)
}

export const useAppMock = (appid: string) => {
  currentAppId.value = appid
  const app = sessionStorage.getItem(appid)
  if (app) {
    const appPar: AppInfo = JSON.parse(app)
    appInfo.id = appPar.id
    appInfo.name = appPar.name
    appInfo.desc = appPar.desc
    appInfo.actions = appPar.actions
    appInfo.models = appPar.models
    appInfo.pages = appPar.pages
  }

  return {
    appInfo,
    // appInfo: readonly(appInfo),
    currentPage: readonly(currentPage),
    currentCom: readonly(currentCom),
    setAppBasic,
    addAppPage,
    editPageConfig,
    changeCurrentPage,
    changeCurrentCom,
  }
}
